#include "mbed.h"
#include "I2C.h"
#include "DX8_API.h"

//#define DX82_ENABLE

#define CHECK_RV(x) do { unsigned char y = x; if(y) {printf("Error: rv=%.2x\n",y); return y;} } while(0)

//#define DEBUG_ENABLE

/* I2C Pins: sda, scl */
//mbed::I2C i2c(GPIO_PIN22, GPIO_PIN23);
static mbed::I2C i2c(PD_0, PD_1);

unsigned char dxif_transfer(unsigned char *buf, unsigned short len)
{
       if (buf[0] & 0x01) { // i2c read
          if(i2c.read(buf[0], (char*)buf+1, len-1)) {
             return 1;
          }
					#ifdef DEBUG_ENABLE
					  int i;
					  printf("dxi2c read: %.2X",buf[0]);
					  for (i = 1; i < len; i++) {
					    if (!((i-1) % 16)) printf("\n");
					    printf("%.2X ", buf[i]);
					  }
					  printf("\n");
					#endif
       }
       else {  // i2c write
					#ifdef DEBUG_ENABLE
					  int j;
					  printf("dxi2c write: %.2X %.2X %.2X %.2X",buf[0],buf[1],buf[2],buf[3]);
					  for (j = 4; j < len; j++) {
							if (!((j-4) % 16)) printf("\n");
							printf("%.2X ", buf[j]);
						}
						printf("\n");
					#endif
          if (i2c.write(buf[0], (char*)buf+1, len-1)) {
             return 1;
          }
       }

      return 0;
}
